package com.bringspring.workflow.form.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.RandomUtil;
import com.bringspring.system.base.exception.WorkFlowException;
import com.bringspring.workflow.engine.util.FlowUtil;
import com.bringspring.workflow.engine.util.ServiceAllUtil;
import com.bringspring.workflow.form.entity.LeaveApplyEntity;
import com.bringspring.workflow.form.mapper.LeaveApplyMapper;
import com.bringspring.workflow.form.model.leaveapply.LeaveApplyForm;
import com.bringspring.workflow.form.service.LeaveApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 流程表单【请假申请】
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月29日 上午9:18
 */
@Service
public class LeaveApplyServiceImpl extends ServiceImpl<LeaveApplyMapper, LeaveApplyEntity> implements LeaveApplyService {

    @Autowired
    private ServiceAllUtil serviceAllUtil;

    @Override
    public LeaveApplyEntity getInfo(String id) {
        QueryWrapper<LeaveApplyEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LeaveApplyEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    @DSTransactional
    public void save(String id, LeaveApplyEntity entity) throws WorkFlowException {
        //表单信息
        if (id == null) {
            entity.setId(RandomUtil.uuId());
            this.save(entity);
            serviceAllUtil.useBillNumber("WCREATOR_TIMELeaveApplyNo");
        } else {
            entity.setId(id);
            this.updateById(entity);
        }
        //流程信息
        FlowUtil.save(id, entity.getFlowId(), entity.getId(), entity.getFlowTitle(), entity.getFlowUrgent(), entity.getBillNo(),entity);
    }

    @Override
    @DSTransactional
    public void submit(String id, LeaveApplyEntity entity, Map<String, List<String>> candidateList) throws WorkFlowException {
        //表单信息
        if (id == null) {
            entity.setId(RandomUtil.uuId());
            this.save(entity);
            serviceAllUtil.useBillNumber("WF_LeaveApplyNo");
        } else {
            entity.setId(id);
            this.updateById(entity);
        }
        //流程信息
        FlowUtil.submit(id, entity.getFlowId(), entity.getId(), entity.getFlowTitle(), entity.getFlowUrgent(), entity.getBillNo(), entity,null, candidateList);
    }

    @Override
    public void data(String id, String data) {
        LeaveApplyForm leaveApplyForm = JsonUtil.getJsonToBean(data, LeaveApplyForm.class);
        LeaveApplyEntity entity = JsonUtil.getJsonToBean(leaveApplyForm, LeaveApplyEntity.class);
        entity.setId(id);
        this.saveOrUpdate(entity);
    }
}
